package org.hitchhike.core.runner;

import java.io.UnsupportedEncodingException;

import org.hitchhike.core.domain.User;
import org.hitchhike.core.enums.Constant;
import org.hitchhike.core.enums.UserStateEnum;
import org.hitchhike.core.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class UserStartupRunner implements CommandLineRunner {

  String image =
      "";


  @Autowired
  protected UserRepository userRepository;

  @Override
  public void run(String... args) throws Exception {
    saveAdmin();
    savePassenger();
    saveCarOwner();
    System.out.println(">>>>>>>>>>>>>>>服务启动执行，初始化系统管理员 <<<<<<<<<<<<<");
  }

  private void savePassenger() throws UnsupportedEncodingException {
    if (userRepository.findByUsername("ck") == null) {
      User user = new User();
      user.setUsername("ck");
      user.setPassword("123456");
      user.setRealName("乘客");
      user.setUserType(Constant.TYPE_1);
      user.setUserState(UserStateEnum.ENABLED);
      user.setImage(image.getBytes("UTF-8"));
      userRepository.save(user);
    }
  }

  private void saveCarOwner() throws UnsupportedEncodingException {
    if (userRepository.findByUsername("sj") == null) {
      User user = new User();
      user.setUsername("sj");
      user.setPassword("123456");
      user.setRealName("车主");
      user.setUserType(Constant.TYPE_2);
      user.setUserState(UserStateEnum.FINISHED);
      user.setImage(image.getBytes("UTF-8"));
      userRepository.save(user);
    }
  }

  private void saveAdmin() throws UnsupportedEncodingException {
    if (userRepository.findByUsername("admin") == null) {
      User user = new User();
      user.setUsername("admin");
      user.setPassword("123456");
      user.setRealName("系统管理员");
      user.setUserType(Constant.TYPE_0);
      user.setUserState(UserStateEnum.ENABLED);
      user.setImage(image.getBytes("UTF-8"));
      userRepository.save(user);
    }
  }
}
